#!/usr/bin/python -S
"""
os_process_test.py
"""

__author__ = 'Andy Chu'


import os
import sys

if __name__ == '__main__':
  sys.path.insert(0, os.path.join(os.path.dirname(sys.argv[0]), '../..'))

import os_process  # module under test
import testy


class OsProcessTest(testy.Test):

  def testResult(self):
    runner = os_process.Runner()
    result = runner.Result(['echo', 'hello'])
    # Ignore Windows/Unix line endings
    self.verify.Equal(result.stdout.rstrip(), 'hello')
    self.verify.Equal(result.stderr, '')
    self.verify.Equal(result.exit_code, 0)

    # Now test it with the shell
    result = runner.Result('echo hello')  # Command string
    # Ignore Windows/Unix line endings
    self.verify.Equal(result.stdout.rstrip(), 'hello')
    self.verify.Equal(result.stderr, '')
    self.verify.Equal(result.exit_code, 0)

  def testStdoutLines(self):
    runner = os_process.Runner()
    out = runner.StdoutLines(['echo', 'hello\nthere\n'])
    self.verify.Equal(
        [line.strip() for line in out], ['hello', 'there', ''])

    # Can't have newlines in shell (at least in Windows)
    out = runner.StdoutLines('echo hello there')

    self.verify.Equal(
        [line.strip() for line in out], ['hello there'])

  def testMakeArgs(self):
    runner = os_process.Runner()
    self.verify.Equal(
        runner._MakeArgs(['ls']),
        (['ls'], {'shell': False, 'universal_newlines': True}))
    self.verify.Equal(
        runner._MakeArgs('ls -l'),
        ('ls -l', {'shell': True, 'universal_newlines': True}))

    runner = os_process.Runner(universal_newlines=False)
    self.verify.Equal(
        runner._MakeArgs('ls -l'),
        ('ls -l', {'shell': True, 'universal_newlines': False}))

    cmd, kwargs = runner._MakeArgs(['foo.py'])
    if sys.platform == 'win32':
      self.verify.Equal(len(cmd), 2)
      self.verify.In('python', cmd[0])
    else:
      self.verify.Equal(len(cmd), 1)
    self.verify.Equal(kwargs, {'shell': False, 'universal_newlines': False})

  def testPipes(self):
    # TODO: Make this test hermetic
    runner = os_process.Runner()

    self.verify.Raises(os_process.Error, runner.Pipes, ['ls'], 'JUNK')

    p = runner.Pipes(['ls'], 'O')
    #print p.stdout.read()

  def testExitCodes(self):
    # TODO: Make this test hermetic
    runner = os_process.Runner()
    runner.Run('exit 1')

    runner = os_process.Runner(check_exit_code=True)
    self.verify.Raises(os_process.Error, runner.Run, 'exit 1')

  def testErrorMessage(self):
    # TODO: Make this test hermetic
    runner = os_process.Runner()
    self.verify.Raises(os_process.Error, runner.Run, ['nonexistent'])
    self.verify.Raises(os_process.Error, runner.Pipes, ['nonexistent'])
    self.verify.Raises(os_process.Error, runner.Result, ['nonexistent'])
    

if __name__ == '__main__':
  testy.RunThisModule()
